<template>
  <div class="sla-container">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="left"
      size="small"
      label-width="140px"
      @submit.native.prevent
    >
      <div class="group">
        <el-form-item label="名称" prop="noticeName">
          <el-input
            v-model.number="form.noticeName"
            placeholder="请输入名称"
            clearable
            maxlength="100"
          />
        </el-form-item>
        <el-form-item label="描述" prop="noticeDescription">
          <el-input
            v-model.number="form.noticeDescription"
            placeholder="请输入描述"
            clearable
            maxlength="500"
          />
        </el-form-item>
        <div class="table-wrap">
          <el-table :data="form.noticeConfigList">
            <el-table-column label="优先级" width="150" align="center">
              <template slot-scope="scope">
                <el-tag :type="setType(scope.row.priority)" size="small">
                  <pre style="margin: 0">{{
                    setPriorityName(scope.row.priority)
                  }}</pre>
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="每个节点约定时长">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'noticeConfigList.' + scope.$index + '.timeout'"
                  :rules="rules.timeout"
                >
                  <el-input
                    v-model.number="scope.row.timeout"
                    class="input-with-select"
                    placeholder="请输入内容"
                    maxlength="2"
                    @blur="handleChangeForm({field:'timeout',index:scope.$index,value:scope.row.timeout})"
                  >
                    <template slot="append">
                      <el-select v-model="scope.row.timeoutUnit">
                        <el-option
                          v-for="(item, index) in dictList.timeEnums"
                          :key="item.label + index"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </template>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="提醒频率" width="200">
              <template slot-scope="scope">
                <el-select v-model="scope.row.remindFrequency" @change="val=>handlRremindFrequency(val,scope.$index)">
                  <el-option
                    v-for="(item, index) in dictList.warnEnums"
                    :key="item.label + index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="首次提醒" width="400">
              <template slot-scope="scope">
                <el-form-item :prop="'noticeConfigList.' + scope.$index + '.firstRemind'" :rules="rules.firstRemind">
                  <el-input
                    v-model.number="scope.row.firstRemind"
                    :disabled="scope.row.remindFrequency == 0"
                    class="input-with-select"
                    placeholder="请输入内容"
                    maxlength="2"
                    @input="handleChangeForm({field:'firstRemind',index:scope.$index,value:scope.row.firstRemind})"
                  >
                    <template slot="prepend"> 到期前 </template>
                    <template slot="append">
                      <el-select v-model="scope.row.firstRemindUnit">
                        <el-option
                          v-for="(item, index) in dictList.timeEnums"
                          :key="item.label + index"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </template>
                  </el-input>
                </el-form-item>

              </template>
            </el-table-column>
            <el-table-column label="提醒间隔">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'noticeConfigList.' + scope.$index + '.remindInterval'"
                  :rules="rules.remindInterval"
                >
                  <el-input
                    v-model.number="scope.row.remindInterval"
                    :disabled="scope.row.remindFrequency != 2"
                    class="input-with-select"
                    placeholder="请输入内容"
                    maxlength="2"
                    @input="handleChangeForm({field:'remindInterval',index:scope.$index,value:scope.row.remindInterval})"
                  >
                    <template slot="append">
                      <el-select v-model="scope.row.remindIntervalUnit">
                        <el-option
                          v-for="(item, index) in dictList.timeEnums"
                          :key="item.label + index"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </template>
                  </el-input>
                </el-form-item>

              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="group">
        <div class="form-group">
          <el-form-item label="API提醒" prop="remindAPI">
            <el-switch
              v-model="form.remindAPI"
              inactive-color=""
              @change="changeApi"
            />
          </el-form-item>

          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="small"
            :disabled="!form.remindAPI"
            @click="addApi"
          >添加提醒</el-button>
          <template v-if="form.remindAPI && form.apiNoticeList.length">
            <div
              v-for="(item, index) in form.apiNoticeList"
              :key="index"
              class="form-group"
            >
              <div class="close-group">
                <span>{{ index >= 9 ? index + 1 : "0" + (index + 1) }}</span>

                <i
                  class="el-icon-close"
                  @click="form.apiNoticeList.splice(index, 1)"
                />
              </div>

              <el-form-item
                required
                label=" "
                label-width="0px"
                class="inline-item"
              >
                <el-form-item
                  :prop="'apiNoticeList.' + index + '.method'"
                  label-width="0px"
                  :rules="rules.method"
                >
                  <el-select
                    v-model="item.method"
                    :popper-append-to-body="false"
                    clearable
                  >
                    <el-option label="get" value="get" />
                    <el-option label="post" value="post" />
                    <el-option label="put" value="put" />
                  </el-select>
                </el-form-item>

                <el-form-item
                  :prop="'apiNoticeList.' + index + '.url'"
                  :rules="rules.url"
                >
                  <el-input
                    v-model="item.url"
                    clearable
                    maxlength="100"
                    @focus="(val) => checkInput(item.url, item, 'url')"
                    @input="(val) => checkInput(val, item, 'url')"
                  /></el-form-item>

                <div class="fx">
                  <el-button
                    v-if="!item.urlFxVisible"
                    type="primary"
                    plain
                    size="small"
                    @click="showFx(item, 'url')"
                  >fx</el-button>

                  <div v-else class="cascader_wrapper">
                    <div class="cascader_top">
                      <span>插入变量</span>

                      <i class="el-icon-close" @click="hiddenFx(item, 'url')" />
                    </div>

                    <el-cascader-panel
                      v-model="item.urlValue"
                      style="width: 100%"
                      clearable
                      size="small"
                      :props="casProps"
                      :options="casOptions"
                      @change="(val) => casClick(val, item, 'url')"
                    />
                  </div>
                </div>
              </el-form-item>

              <el-form-item
                label="请求类型"
                :prop="'apiNoticeList.' + index + '.contentType'"
                :rules="rules.contentType"
              >
                <el-select
                  v-model="item.contentType"
                  clearable
                  placeholder="请选择"
                  :popper-append-to-body="false"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="Headers" prop="headers" class="headers-form">
                <div
                  v-for="(i, idx) in item.headers"
                  :key="idx + '' + idx"
                  class="header-line"
                >
                  <el-input v-model="i.key" clearable style="width: 150px" maxlength="500" />
                  <el-input
                    v-model="i.value"
                    clearable
                    style="margin: 0 10px 0 20px; width: 631px"
                    maxlength="500"
                  />
                  <i
                    v-if="item.headers.length > 1"
                    class="el-icon-circle-close"
                    @click="item.headers.splice(idx, 1)"
                  />
                  <i
                    class="el-icon-circle-plus"
                    @click="item.headers.push({})"
                  />
                </div>
              </el-form-item>

              <el-form-item label="body" prop="body">
                <el-input
                  v-model="item.body"
                  type="textarea"
                  :autosize="{ minRows: 2 }"
                  clearable
                  maxlength="1000"
                  @focus="() => checkInput(item.body, item, 'body')"
                  @input="(val) => checkInput(val, item, 'body')"
                />

                <div class="fx">
                  <el-button
                    v-if="!item.bodyFxVisible"
                    type="primary"
                    plain
                    size="small"
                    @click="showFx(item, 'body')"
                  >fx</el-button>

                  <div v-else class="cascader_wrapper">
                    <div class="cascader_top">
                      <span>插入变量</span>

                      <i
                        class="el-icon-close"
                        @click="hiddenFx(item, 'body')"
                      />
                    </div>

                    <el-cascader-panel
                      v-model="item.bodyValue"
                      style="width: 100%"
                      clearable
                      size="small"
                      :props="casProps"
                      :options="casOptions"
                      @change="(val) => casClick(val, item, 'body')"
                    />
                  </div>
                </div>
              </el-form-item>
            </div>
          </template>
        </div>

        <div class="form-group">
          <el-form-item label="站内信提醒" prop="emailRemind">
            <el-switch
              v-model="form.emailRemind"
              :active-value="1"
              :inactive-value="0"
              inactive-color=""
            />
          </el-form-item>

          <div v-if="form.emailRemind">
            <el-form-item prop="siteNotice.noticeObjects" label="提醒对象">
              <el-checkbox-group v-model="form.siteNotice.noticeObjects">
                <!-- <el-checkbox label="复选框 A" /> -->
                <el-checkbox
                  v-for="item in remindArray"
                  :key="item.label"
                  :label="item.label"
                  :rules="rules.noticeObjects"
                >{{ item.text }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item
              v-if="form.siteNotice.noticeObjects.includes('assignUser')"
              label="指定用户"
              prop="siteNotice.noticeUserIds"
            >
              <el-select
                v-model="form.siteNotice.noticeUserIds"
                multiple
                clearable
                placeholder="请选择"
                :popper-append-to-body="false"
              >
                <el-option
                  v-for="item in noticeUserOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>

            <!--  <el-form-item label="提醒标题" prop="title">
              <el-input
                v-model="form.title"
                clearable
                @focus="(val) => checkInput(form.title, form, 'title')"
                @input="(val) => checkInput(val, form, 'title')"
              />

              <div class="fx">
                <el-button
                  v-if="!form.titleFxVisible"
                  type="primary"
                  plain
                  size="small"
                  @click="showFx(form, 'title')"
                  >fx</el-button
                >

                <div v-else class="cascader_wrapper">
                  <div class="cascader_top">
                    <span>插入变量</span>

                    <i class="el-icon-close" @click="hiddenFx(form, 'title')" />
                  </div>

                  <el-cascader-panel
                    ref="cascaderPanel"
                    v-model="form.titleValue"
                    style="width: 100%"
                    clearable
                    size="small"
                    :props="casProps"
                    :options="casOptions"
                    @change="(val) => casClick(val, form, 'title')"
                  />
                </div>
              </div>
            </el-form-item> -->

            <el-form-item label="提醒内容" prop="siteNotice.content">
              <el-input
                v-model="form.siteNotice.content"
                type="textarea"
                :autosize="{ minRows: 2 }"
                clearable
                maxlength="1000"
                @focus="
                  (val) =>
                    checkInput(
                      form.siteNotice.content,
                      form.siteNotice,
                      'content'
                    )
                "
                @input="(val) => checkInput(val, form.siteNotice, 'content')"
              />

              <div class="fx">
                <el-button
                  v-if="!form.siteNotice.contentFxVisible"
                  type="primary"
                  plain
                  size="small"
                  @click="showFx(form.siteNotice, 'content')"
                >fx</el-button>

                <div v-else class="cascader_wrapper">
                  <div class="cascader_top">
                    <span>插入变量</span>

                    <i
                      class="el-icon-close"
                      @click="hiddenFx(form.siteNotice, 'content')"
                    />
                  </div>

                  <el-cascader-panel
                    v-model="form.siteNotice.contentValue"
                    style="width: 100%"
                    clearable
                    size="small"
                    :props="casProps"
                    :options="casOptions"
                    @change="(val) => casClick(val, form.siteNotice, 'content')"
                  />
                </div>
              </div>
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
    <div class="footer">
      <el-button type="primary" @click="submitForm">保 存</el-button>

      <el-button @click="$router.go(-1)">取 消</el-button>
    </div>
  </div>
</template>

<script>
import {
  getAllUser,
  createNotice,
  getIdNotice,
  updateNotice
} from '@/api/basicConfig/notice.js'
export default {
  beforeRouteLeave(to, from, next) {
    if (to.path.includes('/bpmn/sla/slaList')) {
      to.meta.keepAlive = true
    }
    next()
  },
  data() {
    return {
      form: {
        remindAPI: true,
        emailRemind: 1,
        titleFxVisible: false,
        //  api提醒
        apiNoticeList: [
          {
            urlFxVisible: false,
            bodyFxVisible: false,
            headers: [{}],
            urlValue: [],
            bodyValue: [],
            url: '',
            body: ''
          }
        ],
        // 站内信
        siteNotice: {
          contentFxVisible: false,
          noticeObjects: ['currentUser'],
          content: '',
          contentValue: []
        },

        //  优先级配置
        noticeConfigList: [
          {
            id: null,
            priority: 0,
            timeout: null,
            timeoutUnit: 4,
            firstRemind: 1,
            firstRemindUnit: 2,
            remindInterval: 1,
            remindIntervalUnit: 2,
            remindFrequency: 1
          },
          {
            id: null,
            priority: 1,
            firstRemind: 1,
            firstRemindUnit: 2,
            remindInterval: 1,
            remindIntervalUnit: 2,
            remindFrequency: 1,
            timeout: null,
            timeoutUnit: 4
          },
          {
            id: null,
            priority: 2,
            firstRemind: 1,
            firstRemindUnit: 2,
            remindInterval: 1,
            remindIntervalUnit: 2,
            remindFrequency: 1,
            timeout: null,
            timeoutUnit: 4
          },
          {
            id: null,
            priority: 3,
            firstRemind: 1,
            firstRemindUnit: 2,
            remindInterval: 1,
            remindIntervalUnit: 2,
            remindFrequency: 1,
            timeout: null,
            timeoutUnit: 4
          },
          {
            id: null,
            priority: 4,
            firstRemind: 1,
            firstRemindUnit: 2,
            remindInterval: 1,
            remindIntervalUnit: 2,
            remindFrequency: 1,
            timeout: null,
            timeoutUnit: 4
          }
        ]
      },
      defaultValiteRules: ['noticeName', 'siteNotice.noticeObjects'],
      rules: {
        noticeName: [{ required: true, message: '请输入', trigger: 'blur' }],
        // flowsIds: [
        //   { required: true, message: '请选择流程', trigger: ['change'] }
        // ],
        timeout: [
          { required: true, message: '请输入', trigger: 'blur' },
          { type: 'number', message: '必须为数字值' },
          { validator: this.validateNumber, trigger: 'blur' }
        ],

        firstNoticeTime: [
          { required: true, message: '请输入', trigger: 'blur' },
          { type: 'number', message: '必须为数字值' },
          { validator: this.validateNumber, trigger: 'blur' }
        ],
        intervalTime: [
          { required: true, message: '请输入', trigger: 'blur' },
          { type: 'number', message: '必须为数字值' },
          { validator: this.validateNumber, trigger: 'blur' }
        ],
        noticeObjects: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        userIds: [{ required: true, message: '请选择', trigger: 'change' }],
        content: [{ required: true, message: '请输入', trigger: 'blur' }],
        siteNotice: {
          noticeObjects: [
            { required: true, message: '请输入', trigger: 'change' }
          ]
        },
        firstRemind: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: this.validateMessage, trigger: ['blur', 'change'] },
          { type: 'number', message: '必须为数字值' }
        ],
        method: [
          {
            required: true,
            message: '请选择',
            trigger: 'change'
          }
        ],
        url: [
          {
            required: true,
            message: '请输入url',
            trigger: 'blur'
          }
        ],
        contentType: [
          {
            required: true,
            message: '请选择',
            trigger: 'change'
          }
        ],
        remindInterval: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: this.validateMessage, trigger: ['blur', 'change'] },
          { type: 'number', message: '必须为数字值' }
        ]
      },
      noticeUserOptions: [{ value: 1, label: 'ceshi' }],
      options: [
        { label: 'application/json', value: 'application/json' },
        { label: 'application/xml', value: 'application/xml' },
        { label: 'text/plain', value: 'text/plain' },
        { label: 'multipart/form-data', value: 'multipart/form-data' },
        {
          label: 'application/x-www-form-urlencoded',
          value: 'application/x-www-form-urlencoded'
        }
      ],
      casOptions: [
        {
          label: '默认',
          value: 'normal',
          children: [
            { label: '发起人', value: 'promoter' },
            { label: '团队', value: 'team' },
            { label: '组织', value: 'organization' },
            { label: '创建时间', value: 'createTime' },
            { label: '标题', value: 'title' },
            { label: '流水号', value: 'serialNum' },
            { label: '工单处理页面链接', value: 'handleLink' },
            { label: '流程名称', value: 'flowName' },
            { label: '当前处理步骤', value: 'currentNode' },
            { label: '工单状态', value: 'orderStatus' },
            { label: '当前处理人', value: 'currentHandler' }
          ]
        },
        {
          label: 'SLA管理',
          value: 'SLA',
          children: [
            { label: '约定处理时长', value: 'appointTime' },
            { label: '已过处理时长', value: 'pastTime' },
            { label: '剩余处理时长', value: 'remainingTime' }
          ]
        }
      ],
      casProps: { multiple: true },
      // 数字格式对象
      reverseObj: {},
      // 级联选择器关系数组
      relationArr: [],
      //  mock提醒对象
      remindArray: [
        { label: 'currentUser', text: '当前处理人' },
        { label: 'createUser', text: '发起人' },
        { label: 'assignUser', text: '指定用户' }
      ],
      //  mockTable数据

      dictList: {
        timeEnums: [
          { label: '分', value: 2 },
          { label: '时', value: 3 },
          { label: '天', value: 4 },
          { label: '月', value: 5 }
        ],
        warnEnums: [
          { label: '不提醒', value: 0 },
          { label: '只提醒一次', value: 1 },
          { label: '周期提醒', value: 2 }
        ],
        noTiceTypeEnums: [
          { label: '邮件通知,当前用户', value: 0 },
          { label: '邮件通知', value: 1 },
          { label: 'API通知', value: 2 },
          { label: '站内信通知', value: 3 }
        ]
      }
    }
  },

  mounted() {
    //  如果是点击编辑或复制进来的，获取详情数据
    if (this.$route.query.id) {
      this.getNoticeData()
    }
    this.clearcheck()
    // 整合为{value:label}格式
    this.reverseObj = this.flatten(this.casOptions, 'y')
    this.flattenArr(this.casOptions, [])
    //  获取全部用户
    this.getAllUserData()
  },

  methods: {
    // 获取详情数据
    async getNoticeData() {
      const res = await getIdNotice({ id: this.$route.query.id })
      this.$set(this.form, 'noticeName', res.noticeName)
      this.$set(this.form, 'noticeDescription', res?.noticeDescription)
      this.form.noticeConfigList = this.form.noticeConfigList.map(
        (item, index) => {
          return {
            id: res.noticeConfigList[index].id,
            priority: index,
            firstRemind: res.noticeConfigList[index].firstRemind,
            firstRemindUnit: res.noticeConfigList[index].firstRemindUnit,
            remindInterval: res.noticeConfigList[index].remindInterval,
            remindIntervalUnit: res.noticeConfigList[index].remindIntervalUnit,
            remindFrequency: res.noticeConfigList[index].remindFrequency,
            timeout: res.noticeConfigList[index].timeout,
            timeoutUnit: res.noticeConfigList[index].timeoutUnit
          }
        }
      )
      if (res.apiNoticeList.length > 0) {
        this.form.remindAPI = true
        this.form.apiNoticeList = res.apiNoticeList
        this.form.apiNoticeList = res.apiNoticeList.map((item) => {
          return {
            ...item,
            urlValue: [],
            bodyValue: [],
            urlFxVisible: false,
            bodyFxVisible: false
          }
        })
      }
      this.form.siteNotice = res.siteNotice
      this.form.siteNotice.contentFxVisible = false
      this.form.remindAPI = this.form.apiNoticeList.length > 0
    },
    // 显示fx按钮
    showFx(item, attr) {
      this.checkInput(item[attr], item, attr)
      item[attr + 'FxVisible'] = true
    },
    // 隐藏fx按钮
    hiddenFx(item, attr) {
      item[attr + 'FxVisible'] = false
    },

    // 是否开启api提醒
    changeApi(val) {
      // const obj = {
      //   urlFxVisible: false,
      //   bodyFxVisible: false,
      //   headers: [{}],
      // };
      // this.form.apiNoticeList = !val ? [obj] : this.form.apiNoticeList;
      // this.clearcheck();
    },

    // 增加api提醒项
    addApi() {
      this.form.apiNoticeList.push({
        urlFxVisible: false,
        bodyFxVisible: false,
        headers: [{}],
        urlValue: [],
        bodyArrValue: [],
        url: '',
        body: ''
      })
      this.clearcheck()
    },
    // 输入框的方法
    checkInput(val, Obj, attr) {
      // 关闭fx框
      Obj[attr + 'FxVisible'] = false
      // Variable值初始赋值为input框的值
      Obj[attr + 'Variable'] = val
      // 级联选择器关系数组

      this.relationArr.forEach((item) => {
        // 拼接字符串为`${:}`格式
        const { mixStr, valueStr } = this.tidyStr(item)
        // input输入框有而级联选择器没有
        if (val.includes(mixStr)) {
          if (!Obj[attr + 'Value'].includes(item)) {
            Obj[attr + 'Value'].push(item)
          }
          // 去空值
          Obj[attr + 'Value'] = Obj[attr + 'Value'].filter((item) => {
            return item.length > 0
          })
          // eslint-disable-next-line brace-style
        } // 级联选择器有而输入框没有
        else {
          Obj[attr + 'Value'] = Obj[attr + 'Value'].filter((i) => {
            return i.toString() !== item.toString()
          })

          // 去除空值
          Obj[attr + 'Value'] = Obj[attr + 'Value'].filter((item) => {
            return item.length > 0
          })
        }
        // Variable值替换${ } 内为id格式，用自身replace，避免被重置掉
        Obj[attr + 'Variable'] = Obj[attr + 'Variable'].replace(
          mixStr,
          valueStr
        )
      })
    },
    // 级联选择器选中事件
    casClick(val, Obj, attr) {
      // 级联选择器没有，input有
      this.relationArr.forEach((item) => {
        // 拼接字符串为`${:}`格式
        const { mixStr, valueStr } = this.tidyStr(item)
        const isInside = val.some((i) => {
          return i.toString() === item.toString()
        })
        // input值有但是级联选择器没有
        if (Obj[attr].includes(mixStr)) {
          if (!isInside) {
            Obj[attr] = Obj[attr].replace(mixStr, '')
            Obj[attr + 'Variable'] = Obj[attr + 'Variable'].replace(
              valueStr,
              ''
            )
          }
        } else {
          // input没有，但是级联选择器有
          if (isInside) {
            Obj[attr] += mixStr
            Obj[attr + 'Variable'] += valueStr
          }
        }
      })
    },
    // 整理为${:}字符串
    tidyStr(item) {
      const obj = {
        mixStr: '${',
        valueStr: '${'
      }
      for (let index = 0; index < item.length; index++) {
        obj.mixStr += this.reverseObj[item[index]]
        if (index !== item.length - 1) {
          obj.mixStr += ':'
        }
        obj.valueStr += item[index]
        if (index !== item.length - 1) {
          obj.valueStr += ':'
        }
      }
      obj.mixStr += '}'
      obj.valueStr += '}'
      return obj
    },
    // 对象数组扁平化为对象
    flatten(arr, reverse) {
      let obj = {}
      arr.forEach((item) => {
        const a = reverse ? item.value : item.label
        const b = reverse ? item.label : item.value
        obj[a] = b
        if (item.children) {
          obj = { ...this.flatten(item.children, reverse), ...obj }
        } else return
      })
      return obj
    },
    // 整合父子关系数组 [父，子,孙....]
    flattenArr(arr, allArr) {
      arr.forEach((item) => {
        const temp = [...allArr, item.value]
        if (item.children && item.children) {
          this.flattenArr(item.children, temp)
        } else {
          this.relationArr.push(temp)
        }
      })
    },

    // 保存表单

    submitForm() {
      this.form.noticeConfigList.forEach((i, index) => {
        this.handlRremindFrequency(i.remindFrequency, index)
      })
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.apiNoticeList = !this.form.remindAPI
            ? []
            : this.form.apiNoticeList
          if (
            this.$route.query.type == 'add' ||
            this.$route.query.type == 'copy'
          ) {
            createNotice(this.form).then((res) => {
              this.$message.success('提交成功')
              this.$router.go(-1)
            })
          } else {
            updateNotice({ ...this.form, noticeId: this.$route.query.id }).then(
              (res) => {
                this.$message.success('提交成功')
                this.$router.go(-1)
              }
            )
          }
        } else {
          this.$message.warning('有必填项未填')
          return false
        }
      })
    },

    // 清除验证   在打开弹框事件以及弹框的确认和取消事件 调用此方法

    clearcheck() {
      this.$nextTick(() => {
        this.$refs['form']?.clearValidate()
      })
    },
    //  设置优先级对应的文本信息
    setPriorityName(priority) {
      const PriorityList = {
        0: '极低',
        1: '低',
        2: '中',
        3: '高',
        4: '极高'
      }
      return PriorityList[priority]
    },
    //  设置优先级的颜色
    setType(priority) {
      switch (priority) {
        case 4:
          return 'danger'
          break
        case 3:
          return 'danger'
          break
        case 2:
          return 'warning'
          break
        case 1:
          return 'primary'
          break
        case 0:
          return 'success'
          break
        default:
          break
      }
    },
    //  获取指定用户数据  noticeUserOptions
    getAllUserData() {
      getAllUser().then((res) => {
        this.noticeUserOptions = res.map((i) => {
          return { label: i.name, value: i.id }
        })
      })
    },
    //  校验是否是1-99的数值
    validateNumber(num, val, callback) {
      if (!/^[1-9]\d?$/g.test(val)) {
        return callback(new Error('请输入1-99之间的数字'))
      } else {
        return callback()
      }
    },
    //  校验
    validateMessage(rule, val, callback) {
      if (!val) {
        return callback()
      }
      const fieldArr = rule.field.split('.')
      const index = fieldArr[1]
      const type = fieldArr[2]
      if (!this.form.noticeConfigList[index].timeout) {
        if (this.form.noticeConfigList[index].remindFrequency == 1 && type.includes('firstRemind')) {
          return callback(new Error('首次提醒时间必须小于约定处理时长'))
        } else if (this.form.noticeConfigList[index].remindFrequency == 2) {
          if (type.includes('firstRemind')) {
            return callback(new Error('首次提醒时间必须小于约定处理时长'))
          } else {
            return callback(new Error('提醒时间间隔需要小于约定处理时长'))
          }
        }
      } else {
        //  转换节点约定时长 和 首次提醒时间 和 提醒间隔
        const timeout = this.form.noticeConfigList[index].timeout
        const timeoutUnit = this.form.noticeConfigList[index].timeoutUnit
        const firstRemind = this.form.noticeConfigList[index].firstRemind
        const firstRemindUnit = this.form.noticeConfigList[index].firstRemindUnit
        const newTimeout = timeoutUnit == 5 ? timeout * 30 * 24 * 60 : timeoutUnit == 4 ? timeout * 24 * 60 : timeoutUnit == 3 ? timeout * 60 : timeout
        const newFirstRemind = firstRemindUnit == 5 ? firstRemind * 30 * 24 * 60 : firstRemindUnit == 4 ? firstRemind * 24 * 60 : firstRemindUnit == 3 ? firstRemind * 60 : firstRemind
        const remindInterval = this.form.noticeConfigList[index].remindInterval
        const remindIntervalUnit = this.form.noticeConfigList[index].remindIntervalUnit
        const newRemindInterval = remindIntervalUnit == 5 ? remindInterval * 30 * 24 * 60 : remindIntervalUnit == 4 ? remindInterval * 24 * 60 : remindIntervalUnit == 3 ? remindInterval * 60 : remindInterval
        if (this.form.noticeConfigList[index].remindFrequency == 1) {
          if (newTimeout < newFirstRemind) {
            return callback(new Error('首次提醒时间必须小于约定处理时长'))
          }
        } else if (this.form.noticeConfigList[index].remindFrequency == 2) {
          if (newTimeout < newRemindInterval && type.includes('remindInterval')) {
            return callback(new Error('提醒时间间隔需要小于约定处理时长'))
          }
          if (newTimeout < newFirstRemind && type.includes('firstRemind')) {
            return callback(new Error('首次提醒时间必须小于约定处理时长'))
          }
        } else {
          return callback()
        }
        return callback()
      }
    },
    //  操作表单触发校验
    handleChangeForm({ field, index, value }) {
      if (this.form.noticeConfigList[index].remindFrequency !== 0) {
        this.$refs.form.validateField(`noticeConfigList.${index}.firstRemind`)
        if (this.form.noticeConfigList[index].remindFrequency === 2) {
          this.$refs.form.validateField(`noticeConfigList.${index}.remindInterval`)
        }
      }
    },
    //  触发提醒频率
    handlRremindFrequency(val, index) {
      this.$nextTick(() => {
        if (val == 0) {
          this.$refs.form.clearValidate([`noticeConfigList.${index}.firstRemind`, `noticeConfigList.${index}.remindInterval`])
        } else if (val == 1) {
          this.$refs.form.clearValidate([`noticeConfigList.${index}.remindInterval`])
        } else if (val == 2) {
        // this.$refs.form.clearValidate([`noticeConfigList.${index}.firstRemind`, `noticeConfigList.${index}.remindInterval`])
          this.$refs.form.validateField(`noticeConfigList.${index}.firstRemind`)
          this.$refs.form.validateField(`noticeConfigList.${index}.remindInterval`)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .headers-form{
.el-form-item__content{
    display: flex !important;
    flex-direction: column !important;
  }
}
#app.dark-theme{
  .sla-container{
    background:transparent !important;
  }
  .group{
    background:rgba(59,139,255,.1) !important;
    color:#fff !important;
  }
  .form-group{
    color: #ffffff !important;
    border: 1px solid #00e1e4 !important;
  }
  .table-wrap .input-with-select .el-input-group__append,.el-input-group__prepend{
    background:#061540 !important;
  }
}
::v-deep .el-form .el-form-item--small.el-form-item {
  margin-bottom: 20px;
}
::v-deep .el-table__row .el-form-item--small.el-form-item{
  margin-bottom:0 !important;
}
::v-deep .cell>.el-form-item .el-form-item__error{
  position:static
}
::v-deep .el-form-item__content{
  margin-left:0 !important;
}
.sla-container {
  position:relative;
  background: #f3f5f6;
  width: 100%;
  height: 100%;
  // overflow-y:auto;
  .el-form {
    width: 100%;
    height:calc(100% - 60px);
    overflow: auto;
  }
.footer{
  position: absolute;
  bottom:0;
  width:100%;
  text-align:right;
  padding:10px 20px;
margin:0;
}
  .el-icon-question {
    margin-left: 10px;
    font-size: 16px;
  }
}

// 大框

.group {
  background: #fff;
  width: 100%;
  padding: 20px;
  & + .group {
    margin-top: 20px;
  }
}

.form-group {
  border: 1px solid #ebeef5;
  padding: 15px;
  margin-top: 20px;
}

.split-module {
  & + .split-module {
    border-top: 2px dashed #ebeef5;
    padding-top: 20px;
  }
}

.fx {
  display: inline-block;
  position: relative;
  margin-left: 10px;
  height: 100%;
  .cascader_wrapper {
    position: absolute;
    z-index: 100;
    top: 0px;
    min-width: 180px;
    display: inline-flex;
    flex-direction: column;
    align-items: center;
    .cascader_top {
      width: 100%;
      padding: 2px 10px;
      background: #f6f6f6;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}

.close-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

// 请求头部
.header-line {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .el-icon-circle-close,
  .el-icon-circle-plus {
    font-size: 18px;
    cursor: pointer;
  }

  .el-icon-circle-close {
    color: rgb(199, 194, 194);
  }

  .el-icon-circle-plus {
    margin-left: 7px;
    color: rgb(75, 110, 239);
  }
}

.el-icon-close {
  cursor: pointer;
}

::v-deep {
  // 确保星号位置

  .el-form-item > .el-form-item__label:before {
    content: "*";
    color: #fff;
    margin-right: 4px;
  }

  // 设置统一宽度

  .el-select,
  .el-input,
  .el-textarea,
  .el-input-group {
    width: 800px;
  }

  .table-wrap .el-input-group,
  .table-wrap .el-input,
  .table-wrap .el-select {
    width: 100%;
  }

  .table-wrap .input-with-select .el-input-group__append {
    background-color: #ffffff;
  }
  .table-wrap .input-with-select .el-input-group__prepend {
    background-color: #f5f7fa;
  }

  .el-input-group {
    .el-select {
      width: 100px;
    }

    .el-input.el-input--suffix {
      width: 100px;
    }
  }

  .el-cascader-menu__wrap {
    background: #fff;
  }

  // 一行多个form-item

  .inline-item {
    display: flex;

    & > .el-form-item__content {
      width: 100%;
      display: flex;
      margin-bottom: 0;
      margin-left:0 !important;

      .el-form-item {
        margin-bottom: 0;
      }
    }

    .el-select {
      width: 110px;
      margin-right: 20px;
      .el-input {
        width: 100%;
      }
    }

    .el-form-item__label {
      color: rgba($color: #000000, $alpha: 0);
    }
  }
}
::v-deep .el-tag {
  width: 50px !important;
}
</style>
